package service;

import dao.BookDao;
import dao.BookDaoImpl;
import dao.RelationDao;
import dao.RelationDaoImpl;
import pojo.Book;
import pojo.BookPage;
import pojo.Category;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Tiler on 2020/11/4
 */
public class BookServiceImpl implements BookService {
    private BookDao bookDao = new BookDaoImpl();

    private RelationDao relationDao = new RelationDaoImpl();

    @Override
    public Integer addOneBook(Book book) {
        //插入图书信息
        Integer bookId = bookDao.insertOneBook(book);

        if (bookId == null) { return 0;}

        //插入分类信息
        List<Integer> cids = new ArrayList<>();

        for (Category category : book.getCategories()) {
            cids.add(category.getCategoryId());
        }

        return relationDao.insertBookCategories(bookId, cids);
    }

    @Override
    public BookPage getAllBooks(Map<String, Object> params) {
        Integer page = (Integer) params.get("page");
        Integer size = (Integer) params.get("size");

        Integer start = (page - 1) * size;

        params.put("start", start);
        params.put("length", size);

        List<Book> books = bookDao.selectAllBooks(params);
        Integer count = bookDao.selectBookCount(params);

        Integer total = (count%size==0)? count/size : count/size+1;

        BookPage bookPage = new BookPage();
        bookPage.setBookList(books);
        bookPage.setRowCount(count);
        bookPage.setPageCount(total);
        bookPage.setPageNum(page);
        bookPage.setPageSize(size);

        return bookPage;
    }

    @Override
    public List<Category> getCategoriesByBid(Integer bookId) {

        return relationDao.selectCategoriesByBid(bookId);
    }

    @Override
    public Book getBookById(Integer bookId) {
        return bookDao.selectBookById(bookId);
    }

    @Override
    public Integer setOneBook(Book book) {
        if (bookDao.updateOneBook(book) <= 0) {
            return 0;
        }

        //插入分类信息
        List<Integer> cids = new ArrayList<>();

        if (book.getCategories() != null) {
            for (Category category : book.getCategories()) {
                cids.add(category.getCategoryId());
            }
        }

        relationDao.deleteCategoriesByBid(book.getBookId());

        if (cids.size() > 0) {
            relationDao.insertBookCategories(book.getBookId(), cids);
        }

        return 1;
    }

    @Override
    public Integer delAllBooks(List<Integer> bookIds) {
        return bookDao.deleteAllBooks(bookIds);
    }
}
